﻿using WPay.Domain.Model.DTOs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WPay.Web.API
{
    /// <summary>
    /// Api权限处理类
    /// </summary>
    public class ApiAuthorize : AuthorizeAttribute, IAuthorizationFilter
    {
        public ApiAuthorize()
        {
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {

            //若是需要验证权限访问的 则验证
            if (IsHaveAllow(context.Filters))
            {
                //获取用户凭证信息 若无凭证信息 则拒绝访问
                var user = context.HttpContext.User;
                if (user.Claims.FirstOrDefault() == null)
                {
                    //context.Result = new JsonResult(value: new
                    //{
                    //    success = false,
                    //    errs = new[] { "未经授权的非法请求！" }
                    //});
                    context.Result = new JsonResult(value: new RespDto(false, 401, "登录已过期,请退出重新登录"));
                }
                else
                {
                    //todo 获取验证权限的信息 判断当前用户凭证是否具有权限(后续需进行特定角色验证在进行处理)
                    return;
                }
            }


        }
        /// <summary>
        /// 判断是否需要token验证，true、需token验证；false、无需token验证
        /// </summary>
        /// <param name="filers"></param>
        /// <returns></returns>
        private static bool IsHaveAllow(IList<IFilterMetadata> filers)
        {
            for (int i = 0; i < filers.Count; i++)
            {
                if (filers[i] is IAllowAnonymousFilter)
                {
                    return false;
                }
            }
            return true;

        }
    }
}
